package com.project.forum.controller;

import com.project.forum.common.AppResult;
import com.project.forum.common.ResultCode;
import com.project.forum.config.AppConfig;
import com.project.forum.model.User;
import com.project.forum.services.IUserService;
import com.project.forum.utils.MD5Util;
import com.project.forum.utils.StringUtil;
import com.project.forum.utils.UUIDUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * Created with IntelliJ IDEA.
 * Description:用户注册
 * User:DELL
 * Time:10:03
 */
//用户注册
//对controller接口的描述
@Api(tags = "用户接口")
@Slf4j//日志
//这是一个返回数据的controller
@RestController
//路由映射,一级路径
@RequestMapping("/user")
public class UserController {

    @Resource
    private IUserService userService;
    @ApiOperation("用户注册")
    @PostMapping("/register")
    public AppResult register(@ApiParam("用户名") @RequestParam("username") @NonNull String username,
                              @ApiParam("昵称") @RequestParam("nickname") @NonNull String nickname,
                              @ApiParam("密码") @RequestParam("password") @NonNull String password,
                              @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //检验密码和确认密码是否一致
        if(!password.equals(passwordRepeat)){
            //打印日志
            log.warn(ResultCode.FAILED_TWO_PWD_NOT_SAME.toString());
            //返回错误信息
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }

        //准备数据
        User user=new User();
        user.setUsername(username);
        user.setNickname(nickname);
        //处理密码
        //1.生成盐
        String salt = UUIDUtil.UUID_32();
        //2.加密
        String encryptPassword = MD5Util.md5Salt(password, salt);
        //设置密码和盐
        user.setPassword(encryptPassword);
        user.setSalt(salt);
        //调用service层
        userService.createNormalUser(user);
        //返回成功
        return AppResult.success();
    }

    //用户登录
    @ApiOperation("用户登录")
    @PostMapping("/login")
    public AppResult login(HttpServletRequest request,
                           @ApiParam("用户名") @RequestParam("username") @NonNull String username,
                           @ApiParam("密码") @RequestParam("password") @NonNull String password){
        //调用service中的登录方法，返回user对象
        User user = userService.login(username, password);
        //进行非空校验
        if (user==null){
            //打印日志
            log.warn(ResultCode.FAILED_LOGIN.toString());
            //返回结果
            return AppResult.failed(ResultCode.FAILED_LOGIN);
        }
        //如果登录成功把User对象设置到Session作用域中
        HttpSession session = request.getSession(true);//没有session的时候，创建一个新的
        session.setAttribute(AppConfig.USER_SESSION, user);
        //返回结果
        return AppResult.success();
    }

    //获取用户信息
    @ApiOperation("获取用户信息")
    @GetMapping("/info")
    public AppResult<User> getUserInfo(HttpServletRequest request,//非必写选项
                                       @ApiParam("用户id") @RequestParam(value = "id",required = false) Long id){
        //定义返回的user对象
        User user=null;

        //根据id的值来判断user对象的获取方法，如果id为空
        if(id==null){
            //从session中获取当前登录的用户信息
            HttpSession session = request.getSession(false);
            //从session 中获取当前登录的用户信息
            user = (User)session.getAttribute(AppConfig.USER_SESSION);
        }else {
            //2，如果id不为空，从数据库中获取当前登录的信息
            user = userService.selectById(id);
        }
        //盘点用户对象是否为空
        if (user==null){
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        //返回正常的结果
        return AppResult.success(user);
    }

    @ApiOperation("退出登录")
    @GetMapping("/logout")
    public AppResult logout(HttpServletRequest request){
        //获取session对象
        HttpSession session=request.getSession(false);
        //判断session是否有效
        if (session!=null){
            //打印日志
            log.info("退出成功");
            //表示用户在登录状态，直接销毁session
            session.invalidate();//删除与其相关的所有数据
        }
        return AppResult.success("退出成功");
    }

    @ApiOperation("修改个人信息")
    @PostMapping("/modifyInfo")
    public AppResult modifyInfo(HttpServletRequest request,
                                @ApiParam("用户名") @RequestParam(value = "userName",required = false) String userName,
                                @ApiParam("昵称") @RequestParam(value = "nickname",required = false) String nickname,
                                @ApiParam("性别") @RequestParam(value = "gender",required = false) Byte gender,
                                @ApiParam("邮箱") @RequestParam(value = "email",required = false)  String email,
                                @ApiParam("电话号") @RequestParam(value = "phoneNum",required = false)  String phoneNum,
                                @ApiParam("个人简介") @RequestParam(value = "remark",required = false)  String remark){
        //从session中获取用户id
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //对参数做非空校验（全部为空，则返回错误信息）
        if (StringUtil.isEmpty(userName)&&StringUtil.isEmpty(nickname)
        &&StringUtil.isEmpty(email)&&StringUtil.isEmpty(phoneNum)
        &&StringUtil.isEmpty(remark)&&gender==null){
            //返回错误信息
            return AppResult.failed("请输入要修改的内容");
        }
        //封装对象
        User updateUser = new User();
        updateUser.setId(user.getId());
        updateUser.setUsername(userName);
        updateUser.setNickname(nickname);
        updateUser.setGender(gender);
        updateUser.setEmail(email);
        updateUser.setPhoneNum(phoneNum);
        updateUser.setRemark(remark);
        //调用Service
        userService.modifyInfo(updateUser);
        //查询最新的用户信息
        user=userService.selectById(user.getId());
        //把最新的用户信息设置到session中
        session.setAttribute(AppConfig.USER_SESSION,user);
        //返回结果
        return AppResult.success(user);
    }

    @ApiOperation("修改密码")
    @PostMapping("/modifyPwd")
    public AppResult modifyPassword(HttpServletRequest request,
                                    @ApiParam("原密码") @RequestParam("oldPassword") @NonNull String oldPassword,
                                    @ApiParam("新密码") @RequestParam("newPassword") @NonNull String newPassword,
                                    @ApiParam("确认密码") @RequestParam("passwordRepeat") @NonNull String passwordRepeat){
        //校验新密码和确认密码是否相同
        if (!newPassword.equals(passwordRepeat)){
            //返回结果
            return AppResult.failed(ResultCode.FAILED_TWO_PWD_NOT_SAME);
        }
        //获取当前登录的用户信息
        HttpSession session = request.getSession(false);
        User user = (User) session.getAttribute(AppConfig.USER_SESSION);
        //调用Service
        userService.modifyPassWord(user.getId(),newPassword,oldPassword);
        //销毁session
        if (session!=null){
            session.invalidate();
        }
        //返回结果
        return AppResult.success();

    }

}
